<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { Exercise, ProgressAnalysis, WeaknessAnalysis } from '../../api/exercise'
import { getExerciseList, getExerciseDetail, getExerciseAnalysis, getExerciseWeakness, getRecommendExercises, getPaperList, DifficultyLevel, difficultyLabels, getDifficultyLabel } from '../../api/exercise'
import katex from 'katex'
import 'katex/dist/katex.min.css'

const exercises = ref<Exercise[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')

const columns = [
  { prop: 'exerciseId', label: '题目ID', width: '100' },
  { prop: 'paperTitle', label: '所属题库', width: '150' },
  { prop: 'exerciseContent', label: '题目内容', minWidth: '300' },
  { prop: 'exerciseType', label: '题目类型', width: '120' },
  { prop: 'exerciseDifficulty', label: '难度', width: '120' },
  { prop: 'exerciseSymbol', label: '错误率', width: '120' },
]

interface AnalysisData {
  type: 'detail' | 'analysis'
  data: Exercise | {
    progress?: ProgressAnalysis
    weakness?: WeaknessAnalysis
    recommendations?: Exercise[]
  }
}

const analysisDialogVisible = ref(false)
const currentAnalysis = ref<AnalysisData | null>(null)

// 添加筛选相关的响应式变量
const selectedPaper = ref<number | null>(null)
const selectedType = ref<string | null>(null)
const selectedDifficulty = ref<DifficultyLevel | null>(null)
const paperOptions = ref<{ label: string; value: number }[]>([])
const typeOptions = ['选择题', '填空题', '简答题']
const difficultyOptions = [
  { label: '入门', value: DifficultyLevel.EASY },
  { label: '基础', value: DifficultyLevel.MEDIUM },
  { label: '进阶', value: DifficultyLevel.HARD },
  { label: '挑战', value: DifficultyLevel.VERY_HARD },
  { label: '极限', value: DifficultyLevel.EXTREME }
]

// 获取题库列表
const fetchPaperList = async () => {
  try {
    const { data: { code, data, message } } = await getPaperList()
    if (code === 0 && data) {
      paperOptions.value = data.map(paper => ({
        label: paper.paperTitle || '未命名题库',
        value: paper.paperId
      }))
    } else {
      ElMessage.error(message || '获取题库列表失败')
    }
  } catch (error) {
    console.error('获取题库列表失败:', error)
    ElMessage.error('获取题库列表失败')
  }
}

// 获取题目列表
const fetchExercises = async () => {
  loading.value = true
  try {
    // 先获取题库列表
    const { data: { data: papers = [] } } = await getPaperList()

    // 获取题目列表
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      keyword: searchKeyword.value || undefined,
      paperId: selectedPaper.value || undefined,
      type: selectedType.value || undefined,
      difficulty: selectedDifficulty.value || undefined
    }

    // 打印筛选参数，包含更详细的难度信息
    console.log('筛选参数:', {
      ...params,
      difficulty: selectedDifficulty.value ? {
        value: selectedDifficulty.value,
        label: difficultyLabels[selectedDifficulty.value],
        chineseNumeral: getDifficultyLabel(selectedDifficulty.value)
      } : '全部'
    })

    // 发送请求前打印完整的请求URL和参数
    console.log('请求URL:', '/exercise/list')
    console.log('请求参数:', params)

    const response = await getExerciseList(params)
    
    // 打印返回的数据
    console.log('API返回数据:', response.data)
    
    const { data: { code, data, message } } = response
    if (code === 0 && data) {
      exercises.value = data.list.map(exercise => {
       
        return {
          ...exercise,
          paperTitle: papers.find(paper => 
            paper.paperContent && paper.paperContent.includes(exercise.exerciseId)
          )?.paperTitle || '未知题库',
          exerciseDifficulty: String(exercise.exerciseDifficulty || '')
        }
      })
      total.value = Number(data.total) || 0
    } else {
      ElMessage.error(message || '获取题目列表失败')
    }
  } catch (error) {
    console.error('获取题目列表失败:', error)
    ElMessage.error('获取题目列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchExercises()
}

// 处理每页数量变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchExercises()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchExercises()
}

// 格式化错误率显示
const formatErrorRate = (rate: string) => {
  if (!rate) return '0%'
  return `${(parseFloat(rate) * 100).toFixed(1)}%`
}

// 格式化难度显示
const formatDifficulty = (difficulty: string) => {
  if (!difficulty) {
    return '未知'
  }

  switch (difficulty) {
    case '一': return '入门'
    case '二': return '基础'
    case '三': return '进阶'
    case '四': return '挑战'
    case '五': return '极限'
    default: return '未知'
  }
}

// 获取难度标签类型
const getDifficultyTagType = (difficulty: string) => {
  if (!difficulty) {
    return ''
  }

  // 如果是中文数字，先转换成对应的难度标签
  const difficultyLabel = (() => {
    switch (difficulty) {
      case '一': return '入门'
      case '二': return '基础'
      case '三': return '进阶'
      case '四': return '挑战'
      case '五': return '极限'
      default: return difficulty // 如果已经是标签文本就直接使用
    }
  })()

  // 根据难度标签返回对应的类型
  switch (difficultyLabel) {
    case '入门':
      return 'success'
    case '基础':
      return 'info'
    case '进阶':
      return 'warning'
    case '挑战':
    case '极限':
      return 'danger'
    default:
      return ''
  }
}

// 获取错误率标签类型
const getErrorRateType = (rate: string) => {
  const value = parseFloat(rate)
  if (value >= 0.7) return 'danger'
  if (value >= 0.4) return 'warning'
  return 'success'
}

// 类型判断函数
const isExercise = (data: any): data is Exercise => {
  return data && 'exerciseContent' in data
}

const isAnalysisData = (data: any): data is {
  progress?: ProgressAnalysis
  weakness?: WeaknessAnalysis
  recommendations?: Exercise[]
} => {
  return data && (
    ('progress' in data) ||
    ('weakness' in data) ||
    ('recommendations' in data)
  )
}

// 查看详情
const handleViewDetail = async (row: Exercise) => {
  try {
    const response = await getExerciseDetail(row.exerciseId)
    const { data: { code, data, message } } = response
    if (code === 0 && data) {
      // 转换难度值
      const difficulty = String(data.exerciseDifficulty || '')
      const formattedDifficulty = (() => {
        switch (difficulty) {
          case '一': return '入门'
          case '二': return '基础'
          case '三': return '进阶'
          case '四': return '挑战'
          case '五': return '极限'
          default: return '未知'
        }
      })()

      currentAnalysis.value = {
        type: 'detail',
        data: {
          ...data,
          exerciseDifficulty: formattedDifficulty
        }
      }
      analysisDialogVisible.value = true
    } else {
      ElMessage.error(message || '获取题目详情失败')
    }
  } catch (error) {
    console.error('获取题目详情失败:', error)
    ElMessage.error('获取题目详情失败')
  }
}

// 分析数据
const analyzeExercise = async (row: Exercise) => {
  try {
    const [progressRes, weaknessRes, recommendRes] = await Promise.all([
      getExerciseAnalysis(row.exerciseId),
      getExerciseWeakness(),
      getRecommendExercises()
    ])

    const progress = progressRes.data.data
    const weakness = weaknessRes.data.data
    const recommendations = recommendRes.data.data

    if (progressRes.data.code === 0 && weaknessRes.data.code === 0 && recommendRes.data.code === 0) {
      currentAnalysis.value = {
        type: 'analysis',
        data: {
          progress,
          weakness,
          recommendations
        }
      }
      analysisDialogVisible.value = true
    } else {
      ElMessage.error('获取分析数据失败')
    }
  } catch (error) {
    console.error('获取分析数据失败:', error)
    ElMessage.error('获取分析数据失败')
  }
}

// 处理筛选条件变化
const handleFilterChange = () => {
  console.log('筛选条件变化:', {
    paper: selectedPaper.value,
    type: selectedType.value,
    difficulty: selectedDifficulty.value ? difficultyLabels[selectedDifficulty.value] : '全部'
  })
  currentPage.value = 1
  fetchExercises()
}

// 渲染LaTeX公式
const renderLatex = (text: string) => {
  if (!text) return ''
  
  // 匹配行内公式 $...$ 和行间公式 $$...$$
  return text.replace(/\$\$(.*?)\$\$|\$(.*?)\$/g, (match, displayMode, inlineMode) => {
    const formula = displayMode || inlineMode
    try {
      return katex.renderToString(formula, {
        displayMode: !!displayMode,
        throwOnError: false
      })
    } catch (error) {
      console.error('LaTeX渲染错误:', error)
      return match
    }
  })
}

// 格式化选择题内容
const formatChoiceContent = (content: string) => {
  if (!content) return { question: '', options: [] }
  
  // 使用换行符分割内容
  const parts = content.split('\n').filter(part => part.trim())
  
  // 第一行为题目，处理其中的LaTeX公式
  const question = renderLatex(parts[0])
  
  // 剩余行为选项，处理每个选项中的LaTeX公式
  const options = parts.slice(1).map(option => renderLatex(option.trim()))
  
  return {
    question,
    options
  }
}

// 格式化表格内容
const formatTableContent = (content: string, type: string) => {
  if (!content) return ''
  if (type === '选择题') {
    const { question } = formatChoiceContent(content)
    return question
  }
  return renderLatex(content)
}

onMounted(async () => {
  await fetchPaperList()
  await fetchExercises()
})
</script>

<template>
  <div class="project-manage">
    <div class="page-header">
      <h2>题目管理</h2>
      <p class="description">管理和分析所有题目</p>
    </div>

    <el-card class="filter-card">
      <div class="filter-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索题目内容"
          class="filter-item"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              搜索
            </el-button>
          </template>
        </el-input>

        <el-select
          v-model="selectedPaper"
          placeholder="选择题库"
          clearable
          class="filter-item"
          @change="handleFilterChange"
        >
          <el-option
            v-for="item in paperOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-select
          v-model="selectedType"
          placeholder="题目类型"
          clearable
          class="filter-item"
          @change="handleFilterChange"
        >
          <el-option
            v-for="type in typeOptions"
            :key="type"
            :label="type"
            :value="type"
          />
        </el-select>

        <el-select
          v-model="selectedDifficulty"
          placeholder="难度等级"
          clearable
          class="filter-item"
          @change="handleFilterChange"
        >
          <el-option
            v-for="item in difficultyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </el-card>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="exercises"
        border
        style="width: 100%"
      >
        <el-table-column
          v-for="col in columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          :min-width="col.minWidth"
        >
          <template #default="{ row }">
            <template v-if="col.prop === 'exerciseSymbol'">
              <el-tag :type="getErrorRateType(row.exerciseSymbol)">
                {{ formatErrorRate(row.exerciseSymbol) }}
              </el-tag>
            </template>
            <template v-else-if="col.prop === 'exerciseDifficulty'">
              <el-tag :type="getDifficultyTagType(row.exerciseDifficulty)">
                {{ formatDifficulty(row.exerciseDifficulty) }}
              </el-tag>
            </template>
            <template v-else-if="col.prop === 'exerciseContent'">
              <div v-html="formatTableContent(row.exerciseContent, row.exerciseType)"></div>
            </template>
            <template v-else>
              {{ row[col.prop] }}
            </template>
          </template>
        </el-table-column>
        
        <el-table-column
          fixed="right"
          label="操作"
          width="200"
        >
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleViewDetail(row)"
            >
              查看详情
            </el-button>
            <el-button
              link
              type="primary"
              @click="analyzeExercise(row)"
            >
              分析数据
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 分析对话框 -->
    <el-dialog
      v-model="analysisDialogVisible"
      :title="currentAnalysis?.type === 'detail' ? '题目详情' : '题目分析'"
      width="60%"
    >
      <template v-if="currentAnalysis?.type === 'detail'">
        <div class="detail-content">
          <template v-if="isExercise(currentAnalysis.data)">
            <h3>题目类型</h3>
            <p>{{ currentAnalysis.data.exerciseType }}</p>

            <h3>题目内容</h3>
            <template v-if="currentAnalysis.data.exerciseType === '选择题'">
              <div class="choice-question">
                <p class="question-text" v-html="formatChoiceContent(currentAnalysis.data.exerciseContent).question"></p>
                <div class="options-list">
                  <div 
                    v-for="(option, index) in formatChoiceContent(currentAnalysis.data.exerciseContent).options" 
                    :key="index"
                    class="option-item"
                    v-html="option"
                  >
                  </div>
                </div>
              </div>
            </template>
            <template v-else>
              <p v-html="renderLatex(currentAnalysis.data.exerciseContent)"></p>
            </template>
            
            <h3>答案</h3>
            <p v-html="renderLatex(currentAnalysis.data.exerciseAnswer)"></p>
            
            <h3>难度</h3>
            <el-tag :type="getDifficultyTagType(currentAnalysis.data.exerciseDifficulty)">
              {{ currentAnalysis.data.exerciseDifficulty }}
            </el-tag>
          </template>
        </div>
      </template>
      
      <template v-else-if="currentAnalysis?.type === 'analysis'">
        <div class="analysis-content">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card class="analysis-card">
                <template #header>
                  <div class="card-header">
                    <span>完成进度</span>
                  </div>
                </template>
                <template v-if="isAnalysisData(currentAnalysis.data) && currentAnalysis.data.progress">
                  <el-progress
                    type="circle"
                    :percentage="currentAnalysis.data.progress.percentage"
                  />
                  <div class="progress-stats">
                    <p>总题数: {{ currentAnalysis.data.progress.totalExercises }}</p>
                    <p>已完成: {{ currentAnalysis.data.progress.completedExercises }}</p>
                  </div>
                </template>
              </el-card>
            </el-col>
            
            <el-col :span="16">
              <el-card class="analysis-card">
                <template #header>
                  <div class="card-header">
                    <span>薄弱环节</span>
                  </div>
                </template>
                <template v-if="isAnalysisData(currentAnalysis.data) && currentAnalysis.data.weakness">
                  <div class="weakness-section">
                    <div class="weak-areas">
                      <h4>需要改进的领域</h4>
                      <el-tag
                        v-for="area in currentAnalysis.data.weakness.weakAreas"
                        :key="area"
                        class="weakness-tag"
                        type="warning"
                      >
                        {{ area }}
                      </el-tag>
                    </div>
                    <div class="suggestions">
                      <h4>改进建议</h4>
                      <ul>
                        <li 
                          v-for="suggestion in currentAnalysis.data.weakness.improvementSuggestions"
                          :key="suggestion"
                        >
                          {{ suggestion }}
                        </li>
                      </ul>
                    </div>
                  </div>
                </template>
              </el-card>
            </el-col>
          </el-row>
          
          <el-card class="analysis-card" style="margin-top: 20px;">
            <template #header>
              <div class="card-header">
                <span>推荐练习</span>
              </div>
            </template>
            <template v-if="isAnalysisData(currentAnalysis.data) && currentAnalysis.data.recommendations">
              <el-table :data="currentAnalysis.data.recommendations" border>
                <el-table-column prop="exerciseContent" label="题目内容" />
                <el-table-column prop="exerciseType" label="类型" width="120" />
                <el-table-column prop="exerciseDifficulty" label="难度" width="120" />
              </el-table>
            </template>
          </el-card>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.project-manage {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.description {
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 24px;
}

.filter-container {
  display: flex;
  gap: 16px;
  align-items: center;
}

.filter-item {
  min-width: 150px;
}

.table-card {
  margin-bottom: 24px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-content h3 {
  margin-top: 20px;
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
}

.detail-content p {
  margin: 0;
  line-height: 1.6;
}

.analysis-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.weakness-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

.analysis-content .el-row {
  margin-bottom: 20px;
}

.progress-stats {
  margin-top: 16px;
  text-align: center;
}

.progress-stats p {
  margin: 4px 0;
  color: #606266;
}

.weakness-section {
  padding: 0 16px;
}

.weakness-section h4 {
  margin: 12px 0;
  color: #303133;
  font-size: 14px;
}

.suggestions ul {
  padding-left: 20px;
  margin: 8px 0;
}

.suggestions li {
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.choice-question {
  margin: 10px 0;
}

.question-text {
  font-weight: 500;
  margin-bottom: 15px;
  line-height: 1.6;
}

.options-list {
  padding-left: 20px;
}

.option-item {
  margin: 8px 0;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.detail-content :deep(.katex) {
  font-size: 1.1em;
}

.detail-content :deep(.katex-display) {
  margin: 1em 0;
  overflow-x: auto;
  overflow-y: hidden;
}

.option-item :deep(.katex) {
  font-size: 1em;
}

.el-table :deep(.katex) {
  font-size: 1em;
}

.el-table :deep(.katex-display) {
  margin: 0.5em 0;
  overflow-x: auto;
  overflow-y: hidden;
}

/* 确保表格单元格内的公式不会溢出 */
.el-table :deep(.cell) {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
</style>